package com.slipper.system.ai.controller;

import com.slipper.core.gson.GsonUtil;
import com.slipper.system.ai.vo.AiModelVO;
import com.slipper.util.*;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.slipper.system.ai.service.AiModelService;
import com.slipper.system.ai.bo.AiModelBO;
import com.slipper.constants.Constants;

import java.nio.charset.StandardCharsets;
import java.util.Date;

@RestController
@RequestMapping("/system/aiModel")
public class AiModelController {
    @Resource
    private AiModelService aiModelService;
    
    @PostMapping(value = "/queryBy")
    public String queryBy(@RequestBody AiModelBO bo) {
        if(Tool.isBlank(bo.getId())) {
            return ResultUtil.failureResult("数据获取失败！");
        }
        return ResultUtil.successResult(aiModelService.queryBy(bo.getId()));
    }

    @PostMapping(value = "/queryList")
    public String queryList(@RequestBody AiModelBO bo) {
        return ResultUtil.successResult(aiModelService.queryList(bo));
    }
    
    @PostMapping(value = "/queryPage")
    public String queryPage(@RequestBody AiModelBO bo) {
        return ResultUtil.successResult(aiModelService.queryPage(bo));
    }

    @PostMapping(value = "/save")
    public String save(@RequestBody AiModelBO bo) {
        bo.setOperateId(Constants.getCurrentUser().getEmployeeId());
        return ResultUtil.saveResult(aiModelService.save(bo), bo);
    }

    @PostMapping(value = "/delete")
    public String delete(@RequestBody AiModelBO bo) {
        return ResultUtil.deleteResult(aiModelService.delete(bo));
    }

    @PostMapping(value = "/exportData")
    public void exportData(HttpServletResponse response, @RequestBody AiModelBO bo) {
        AiModelVO vo = new AiModelVO();
        vo.setAiModelList(aiModelService.queryList(bo));
        String fileName = "model-" + DateUtil.format(new Date(), "dd-HH-mm-ss") + ".dat";
        FileUtil.downloadContent(response, fileName, AESUtil.encrypt(GsonUtil.toJson(vo)));
    }

    @PostMapping(value = "/importData")
    public String importData(AiModelBO bo) {
        if (bo.getFile() == null) {
            return ResultUtil.failureResult("请选择上传文件！");
        }
        try {
            String content = new String(bo.getFile().getBytes(), StandardCharsets.UTF_8);
            AiModelVO vo = GsonUtil.fromJson(AESUtil.decrypt(content), AiModelVO.class);
            aiModelService.saveList(vo.getAiModelList());
            return ResultUtil.successResult("导入供应商模型成功。");
        } catch (Exception e) {
            return ResultUtil.failureResult("文件解释出错！");
        }
    }
}
